package com.geor.gcv.ict.train;

import org.opencv.core.Mat;
import org.opencv.core.TermCriteria;
import org.opencv.ml.CvSVM;
import org.opencv.ml.CvSVMParams;

import com.geor.gcv.core.mat.Mats;

/**
 * 机器学习 ：支持向量机实现类
 * 
 * @author Administrator
 *
 */
public class MlSVM implements Ml {
	private CvSVM svm = new CvSVM();
	public boolean isSuccess = false;

	@Override
	public void train(Mat trainData, Mat label, String out) {
		CvSVMParams params = initSVMParams(CvSVM.C_SVC, CvSVM.LINEAR, new TermCriteria(1, (int) 1e7, 1e-6));
		svm.train(trainData, label, new Mat(), new Mat(), params);
		svm.save(out);
	}

	private CvSVMParams initSVMParams(int svm_type, int kernel_type, TermCriteria criteria) {
		CvSVMParams params = new CvSVMParams();
		params.set_svm_type(svm_type);
		params.set_kernel_type(kernel_type);
		params.set_term_crit(criteria);
		return params;
	}

	@Override
	public float predict(Mat sample) {
		try {
			if (!isSuccess)
				new RuntimeException("svm未加载配置文件");
			float response = svm.predict(sample);
			return response;
		} finally {
			Mats.releseMat(sample);
		}
	}

	@Override
	public void load(String path) throws Exception {
		try {
			svm.load(path);
		} catch (Exception e) {
			isSuccess = false;
			throw new Exception();
		}
		isSuccess = true;
	}

	@Override
	public boolean isSuccess() {
		if (svm.get_support_vector_count() == 0 && svm.get_var_count() == 0) {
			return false;
		}
		return true;
	}

}
